import os

from flask import Flask, render_template, request
from dao.person_dao import personDao
from dao.user_dao import userDao
from models.user import User
from utils.JsonResponse import JsonResponse

app = Flask(__name__)


@app.route('/')
def print_hi():
    username = 'Grey Li'
    movies = [
        {'title': 'My Neighbor Totoro', 'year': '1988'},
        {'title': 'Dead Poets Society', 'year': '1989'},
        {'title': 'A Perfect World', 'year': '1993'},
        {'title': 'Leon', 'year': '1994'},
        {'title': 'Mahjong', 'year': '1996'},
        {'title': 'Swallowtail Butterfly', 'year': '1996'},
        {'title': 'King of Comedy', 'year': '1999'},
        {'title': 'Devils on the Doorstep', 'year': '1999'},
        {'title': 'WALL-E', 'year': '2008'},
        {'title': 'The Pork of Music', 'year': '2012'},
    ]
    return render_template("index.html", name=username, movies=movies)


# 获取Get请求的路径参数
@app.route("/getPathVariable/<username>", methods=['Get'])
def getPathVariable(username):
    print("接收到get请求的路径参数, username: ", username)
    return JsonResponse.JsonResp(200, True, {"username": username}, "接收Get请求的路径变量成功")


# 获取Get请求的Url参数
@app.route("/getUrlVariable", methods=['Get'])
def getUrlVariable():
    params = request.args
    print(params)
    username = params.get("username")
    password = params.get("password")
    print("接收到form形式参数：", "username: ", username, "password: ", password)
    return JsonResponse.JsonResp(200, True, {"username": username, "password": password}, "获取Get请求的Url参数成功")


# 获取Post请求，表单格式请求参数
@app.route("/formData", methods=['Post'])
def formData():
    formdata = request.form  # 表单数据
    username = formdata["username"]
    password = formdata["password"]
    print("接收到form形式参数：", "username: ", username, "password: ", password)
    return f'username:{username},password:{password}'


# 获取Post请求json格式请求参数
@app.route("/jsonData", methods=['Post'])
def jsonData():
    jsondata = request.get_json()
    username = jsondata["username"]
    password = jsondata["password"]
    print("接收到json形式参数：", "username: ", username, "password: ", password)
    return JsonResponse.JsonResp(200, True, jsondata, "获取json格式数据成功")


# person表的增删改查操作
person_dao = personDao()


# Person表的增删改查

# 查询数据
@app.route("/getAllPerson", methods=['Get'])
def getPersonsList():
    querySql = "select * from person"
    result = person_dao.queryPerson(querySql, None)
    return JsonResponse.JsonResp(200, True, result, "获取person表数据成功")


# 增加数据
@app.route("/insertPerson", methods=['Post'])
def insertPerson():
    data = request.get_json()
    # 如果参数不是json数组格式，则转为数组
    if type(data).__name__ != 'list':
        data = [data]
    print("获取到的json数据: ", data)
    # 将json数组中的value获取转成元组数据
    params = []
    for item in data:
        value = ()
        for K, V in item.items():
            value = value + (V,)
        params.append(value)
    print("元组参数: ", params)
    insertSql = "insert into person(username, gender, email, age) values (%s, %s, %s, %s)"
    rowCount = person_dao.insertPerson(insertSql, params)
    return JsonResponse.JsonResp(200, True, {"rowCount": rowCount}, "插入Person数据成功")


# 删除数据
@app.route("/deletePerson", methods=['Get'])
def deletePerson():
    params = request.args
    ids = params.get("id")
    ids = ids.split(",")
    ids = list(map(int, ids))
    print("获取到id数组：", ids)
    deleteSql = "delete from person where user_id in (%s)"
    rowCount = person_dao.deletePerson(deleteSql, ids)
    return JsonResponse.JsonResp(200, True, {"rowCount": rowCount}, "删除Person数据成功")


# 更新数据
@app.route("/updatePerson", methods=['Post'])
def updatePerson():
    data = request.get_json()
    username = data.get("username")
    gender = data.get("gender")
    email = data.get("email")
    age = int(data.get("age"))
    user_id = int(data.get("id"))
    updateSql = "update person set username = %s, gender = %s, email = %s, age = %s where user_id = %s "
    params = (username, gender, email, age, user_id)
    print("接受的参数", params)
    rowCount = person_dao.updatePerson(updateSql, params)
    return JsonResponse.JsonResp(200, True, {"rowCount": rowCount}, "更新Person数据成功")


# user表的增删改查
user_Dao = userDao()


# 用字典创建对象
def dictToUser(d):
    user = User(id=d['id'], username=d['username'], password=d['password'], age=d['age'],
                gender=d['gender'], address=d['address'], email=d['email'])
    return user


@app.route("/insertUser", methods=['Post'])
def insertUser():
    data = request.get_json()
    # 如果参数不是json数组格式，则转为数组
    if type(data).__name__ != 'list':
        data = [data]
    print("获取到的json数据: ", data)
    userList = []
    for item in data:  # 将json数据转为实体对象
        user = dictToUser(item)
        userList.append(user)
    user_Dao.insertUser(userList)  # 插入多条数据
    return JsonResponse.JsonResp(200, True, userList, "插入数据成功")


@app.route("/deleteUser", methods=['Get'])
def deleteUser():
    params = request.args
    ids = params.get("id")  # 5,8,9
    ids = ids.split(",")  # [5, 8, 9]
    ids = list(map(int, ids))  # int[]
    rowCount = user_Dao.deleteUser(ids)
    return JsonResponse.JsonResp(200, True, {"rowCount": rowCount}, "成功删除{}条数据".format(rowCount))


@app.route("/updateUser", methods=['Post'])
def updateUser():
    data = request.get_json()
    user = dictToUser(data)
    rowCount = user_Dao.updateUser(user)
    return JsonResponse.JsonResp(200, True, {"rowCount": rowCount}, "成功更新{}条数据".format(rowCount))


@app.route("/queryUser", methods=['Post'])
def queryUser():
    data = request.get_json()
    user = dictToUser(data)
    result = user_Dao.queryUser(user)
    return JsonResponse.JsonResp(200, True, result, "查询数据成功")


# 文件的上传下载
@app.route("/uploadFile", methods=['Post'])
def uploadFile():
    fileData = request.files
    # 需求：读取file1的内容写入到file2，并将file2保存到本地
    file1 = fileData.get("file1")
    file2 = fileData.get("file2")
    if file1 is None:
        return JsonResponse.JsonResp(500, False, None, "接受的file1为None")
    if file2 is None:
        return JsonResponse.JsonResp(500, False, None, "接受的file2为None")

    file1_content = file1.read().decode("utf-8")
    file2_content = file2.read().decode("utf-8")

    savePath = "G:\\a"
    saveFileType = os.path.splitext(file2.filename)[-1]
    file3Name = savePath + saveFileType
    if os.path.isfile(file3Name):
        return JsonResponse.JsonResp(200, False, None, "文件file3已存在")
    else:
        file3 = open(file3Name, 'w')
        file3.write(file1_content+"\n\n")
        file3.write(file2_content)
        file3.close()
        return JsonResponse.JsonResp(200, True, None, "file1和file2保存成功")


# 程序入口
if __name__ == '__main__':
    app.run(host="localhost", port=8080, load_dotenv=True)  # 配置ip,端口
